package com.ruoyi.framework.config

import com.alibaba.fastjson2.JSON
import com.alibaba.fastjson2.JSONReader
import com.alibaba.fastjson2.JSONWriter
import com.alibaba.fastjson2.filter.Filter
import com.ruoyi.common.constant.Constants
import org.springframework.data.redis.serializer.RedisSerializer
import org.springframework.data.redis.serializer.SerializationException
import org.springframework.lang.Nullable
import java.nio.charset.Charset

/**
 * Redis使用FastJson序列化
 *
 * @author ruoyi
 */
class FastJson2JsonRedisSerializer<T>(private val clazz: Class<Any>) : RedisSerializer<T?> {
    @Throws(SerializationException::class)
    override fun serialize(t: T?): ByteArray {
        return if (t == null) {
            ByteArray(0)
        } else JSON.toJSONString(t, JSONWriter.Feature.WriteClassName).toByteArray(DEFAULT_CHARSET)
    }

    @Throws(SerializationException::class)
    override fun deserialize(@Nullable bytes: ByteArray?): T? {
        if (bytes == null || bytes.isEmpty()) {
            return null
        }
        val str = String(bytes, DEFAULT_CHARSET)
        return JSON.parseObject(str, clazz, AUTO_TYPE_FILTER) as T?
    }

    companion object {
        val DEFAULT_CHARSET: Charset = Charset.forName("UTF-8")
        val AUTO_TYPE_FILTER: Filter = JSONReader.autoTypeFilter(*Constants.JSON_WHITELIST_STR)
    }
}
